package com.sound.controller;

import com.google.common.primitives.Longs;
import com.sound.common.ParamCode;

import com.sound.common.Response;
import com.sound.model.AudioModel;
import com.sound.model.RecentAlbumModel;
import com.sound.model.RecentAudioModel;
import com.sound.model.UserModel;
import com.sound.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Api(tags="音频")
@RequestMapping(path="/audio")
public class AudioController extends BaseController<AudioModel>{

	private static final Logger logger = LoggerFactory.getLogger(AudioController.class);
	
	@Autowired
	private RestTemplate restTemplate ;
	
	@Autowired
	private AudioService audioService;
	
	@Autowired
	private AlbumService albumService;

	@Autowired
	private RecentAudioService recentAudioService;

	@Autowired
	private RecentAlbumService recentAlbumService;

	@Autowired
	private RedisService redisService;

	
	@Value("${netty.server.url}")
	private String nettyServerURL;
	
	/**
	 * 根据音频id查找音频详情
	 * @param id
	 * @return
	 */
	@GetMapping(path="/findById.do")
	@ApiOperation(value = "根据音频id查找音频详情",tags = "")

	public Response<AudioModel> findById(Long id) {
		Response<AudioModel> resp = new Response<AudioModel>();
		try {
			AudioModel model =  audioService.findById(id);
			resp.setData(model);
			resp.setRespone(ParamCode.SUCSESS);
			return resp;
		}catch (Exception e){
			logger.error("audio findById fail:",e);
			resp.setRespone(ParamCode.FAIL);
			return resp;
		}

	}

	@GetMapping(path="/findAllByAlbumId")
	@ApiOperation(value = "根据albumId下所有音频",tags = "",response = AudioModel.class)
	public Response<Iterable<AudioModel>> findAll(Long albumId) {
		AudioModel audioModel = new AudioModel();
		audioModel.setAlbumId(albumId);
		return super.findAll(audioModel);
	}

	@GetMapping(path="/findByPage")
	@ApiOperation(value = "分页查找音频",tags = "",response = AudioModel.class)
	public Response<Page<AudioModel>> findByPage(int page,int size) {
		Response<Page<AudioModel>> resp = new Response<Page<AudioModel>>(true);

		Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
		PageRequest pageable = PageRequest.of(page, size,sort);
		try {
//			Example<AudioModel> t = Example.of(new AudioModel());
			Page<AudioModel> p= audioService.findAll(pageable);
			resp.setRespone(ParamCode.SUCSESS);
			resp.setData(p);
			return resp;
		}catch (Exception e){
			logger.error("audio findByPage fail",e);
			resp.setRespone(ParamCode.FAIL);
			return resp;
		}

	}

	/**
	 * 专辑播放列表
	 * @param deviceId
	 * @param req
	 * @return
	 */

	@PostMapping(path="/play.do")
	@ApiOperation(value = "专辑播放列表",tags = "")
	public Response<String> play(String audioIds,@RequestParam(value = "deviceId") String deviceId,@RequestParam(value = "opCpde")String opCode,HttpServletRequest req){
		Response<String> resp = new Response<String>(true);
		String[]  sts = audioIds.split(",");
		List<Long> ids = new ArrayList<>();
		for(String id:sts){
			ids.add(Long.valueOf(id));
		}

		UserModel user = redisService.getUserInfo(req);

		try {
			for(int i = 0;i<ids.size();i++) {
				AudioModel audioModel = audioService.findById(ids.get(i));
				if(audioModel == null){
					continue;
				}
				albumService.play(audioModel.getAlbumId());
				audioModel.setPlayCount(audioModel.getPlayCount()+1);
				RecentAudioModel model1 = new RecentAudioModel();
				model1.setUserId(user.getUserId());
				model1.setAudioId(ids.get(i));
				List<RecentAudioModel> list = recentAudioService.findAll(model1);//只有一条
				for(RecentAudioModel each:list) {
					each.setPlaydate(new Date());
					recentAudioService.save(each);
				}
				
			}

			Iterable<AudioModel> audioModels =  this.service.findAllById(ids);
			String body = restTemplate.postForObject(nettyServerURL+"/remote/play/{userId}/{deviceId}/{opCode}", audioModels,String.class,user.getUserId(),deviceId,opCode);
			//入库最近专辑和最近音频
			if(ids.size()>0){
				AudioModel audioModel = audioService.findById(ids.get(0));
				if(audioModel != null){
					RecentAlbumModel recentAlbumModel = new RecentAlbumModel();
					recentAlbumModel.setUserId(user.getUserId());
					recentAlbumModel.setAlbumId(audioModel.getAlbumId());
					recentAlbumService.save(recentAlbumModel);
				}

			}
			if(!"000".equals(body)) {
				resp.setCode("00100");
				resp.setMsg(body);
			}
			resp.setData(body);
		}catch(Exception e) {
			logger.error("audio play fail",e);
			resp.setRespone(ParamCode.FAIL);
		}
		return  resp; 

	}
	
}